package org.ecloud.base.stopwatch;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
@Scope("prototype")
public class StopWatchAspect {

	private static Logger logger = LoggerFactory.getLogger(StopWatchAspect.class);
	private StopWatch watch = new StopWatch();
	@Pointcut("execution(public * org.ecloud..*.provider..*.*(..))")
	public void beforeCut(){}
	@Pointcut("execution(public * org.ecloud..*.provider..*.*(..))")
	public void afterCut(){}
	
	@Before("beforeCut()")
	public void doBefore(JoinPoint joinPoint) {
		String method = getMethod(joinPoint);
		watch.start(method);
	}
	
	@After("afterCut()")
	public void doAfter(JoinPoint joinPoint) {
		watch.stop();
		logger.debug("{} used {} ms.", watch.getLastTaskName(), watch.getLastTaskTimeMillis());
		//logger.debug("\n{}", watch.prettyPrint());
	}
	
	private String getMethod(JoinPoint joinPoint){
		MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String className = method.getDeclaringClass().getName();
        
        return className + "." + method.getName();
	}
	
}
